package com.cspg.design.ui.workmap;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.cspg.design.CheckPermissionsActivity;
import com.cspg.design.R;
import com.cspg.design.ui.project.ProjectTotal;
import com.cspg.design.utils.NotificationUtils;


import java.util.ArrayList;
import java.util.List;

public class WorkMapActivity extends CheckPermissionsActivity implements View.OnClickListener {

    private Button mForegroundBtn;
    private boolean isEnableLocInForeground = false;
    private LocationClient mClient;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Notification mNotification;
    private TextView mTextView;
    private boolean isFirstLoc = true;
    private MyLocationListener myLocationListener;
    private ImageButton mBtnExport;

    private LatLng  preLatLng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_map);
//        getSupportActionBar().hide();
//        StatusBarUtil.setLightStatusBar(this,false,true);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mMapView = (MapView) findViewById(R.id.mv_foreground);
        mTextView = (TextView) findViewById(R.id.reslut_tv);
        mTextView.invalidate();
        //隐藏缩放控件
        mMapView.showZoomControls(false);
        //隐藏比例尺
        mMapView.showScaleControl(false);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBtnExport = findViewById(R.id.btn_map_export);
        mBtnExport.setOnClickListener(this);
        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        mForegroundBtn = (Button) findViewById(R.id.bt_foreground);
        mForegroundBtn.setOnClickListener(this);
        initLocation();
        initNotification();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.e("LatLng" , latLng.latitude +"/////" + latLng.longitude);

                View marker_temp = LayoutInflater.from(getApplicationContext()).inflate(R.layout.marker_text_up_img_down,null);
                TextView marker_tv_temp  = (TextView)marker_temp.findViewById(R.id.baidumap_custom_text);
                ImageView marker_img_temp = (ImageView) marker_tv_temp.findViewById(R.id.baidumap_custom_img);
                marker_tv_temp.setText("xxx");
//                marker_img_temp.setImageResource(R.drawable.icon_mark);
//                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_mark);
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(marker_temp);
                OverlayOptions options = new MarkerOptions().position(latLng).icon(bitmapDescriptor).title("mm").draggable(true);
                mBaiduMap.addOverlay(options);
                if (preLatLng == null)
                {
                    preLatLng = latLng;
                }
                else
                {
                    List<LatLng> points = new ArrayList<>();
                    points.add(preLatLng);
                    points.add(latLng);
                    preLatLng = latLng;
                    OverlayOptions mOverLayerOptions = new PolylineOptions().width(5).color(Color.RED).points(points);
                    mBaiduMap.addOverlay(mOverLayerOptions);
                }
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {

            }
        });
        mBaiduMap.setOnPolylineClickListener(new BaiduMap.OnPolylineClickListener() {
            @Override
            public boolean onPolylineClick(Polyline polyline) {
                if (polyline != null)
                {
                    polyline.setColor(R.color.colorPrimaryDark);
                    return  true;
                }
                return  false;
            }
        });
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                Log.e("LatLng" , latLng.latitude +"//Long///" + latLng.longitude);
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker != null)
                {
                    Log.e("marker", marker.getTitle());
                }
                return false;
            }
        });
        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {

            }

            @Override
            public void onMarkerDragStart(Marker marker) {

            }
        });
    }

    /**
     * 初始化定位参数
     */
    private void initLocation() {
        // 创建定位客户端
        mClient = new LocationClient(this);
        myLocationListener = new MyLocationListener();
        // 注册定位监听
        mClient.registerLocationListener(myLocationListener);
        LocationClientOption mOption = new LocationClientOption();
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        mOption.setScanSpan(1000);
        // 可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        mOption.setCoorType("bd09ll");
        // 可选，默认false，设置是否开启Gps定位
        mOption.setOpenGps(true);
        // 设置定位参数
        mClient.setLocOption(mOption);
//        mClient.start();
    }

    /**
     * 初始化前台服务
     */
    private void initNotification () {
        //设置后台定位
        //android8.0及以上使用NotificationUtils
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationUtils notificationUtils = new NotificationUtils(this);
            Notification.Builder builder = notificationUtils.getAndroidChannelNotification
                    ("适配android 8限制后台定位功能", "正在后台定位");
            mNotification = builder.build();
        } else {
            //获取一个Notification构造器
            Notification.Builder builder = new Notification.Builder(WorkMapActivity.this);
            Intent nfIntent = new Intent(WorkMapActivity.this, WorkMapActivity.class);

            builder.setContentIntent(PendingIntent.
                    getActivity(WorkMapActivity.this, 0, nfIntent, 0)) // 设置PendingIntent
                    .setContentTitle("适配android 8限制后台定位功能") // 设置下拉列表里的标题
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentText("正在后台定位") // 设置上下文内容
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

            mNotification = builder.build(); // 获取构建好的Notification
        }
        mNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case  R.id.bt_foreground:
                if(isEnableLocInForeground){
                    //关闭后台定位（true：通知栏消失；false：通知栏可手动划除）
                    mClient.disableLocInForeground(true);
                    isEnableLocInForeground = false;
                    mForegroundBtn.setText(R.string.startforeground);
                    mClient.stop();
                } else {
                    //开启后台定位
                    // 将定位SDK的SERVICE设置成为前台服务, 提高定位进程存活率
                    mClient.enableLocInForeground(1, mNotification);
                    isEnableLocInForeground = true;
                    mForegroundBtn.setText(R.string.stopforeground);
                    mClient.start();
                }
                break;
            case R.id.btn_map_export:
                startActivity(new Intent(this, ProjectTotal.class));
                break;
        }

    }

    /**
     * 定位信息回调
     */
    class  MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mMapView == null) {
                return;
            }
            bdLocation.setLatitude(26.56819);
            bdLocation.setLongitude(106.7145);
            MyLocationData locData = new MyLocationData.Builder().accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            //地图SDK处理
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            StringBuffer sb = new StringBuffer(256);
            sb.append("纬度: ");
            sb.append(bdLocation.getLatitude()+" , ");
            sb.append( "经度: ");
            sb.append(bdLocation.getLongitude()+"\n");
            if (null != mTextView){
                mTextView.append(sb.toString());
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mMapView = null;
        // 关闭前台定位服务
        mClient.disableLocInForeground(true);
        // 取消之前注册的 BDAbstractLocationListener 定位监听函数
        mClient.unRegisterLocationListener(myLocationListener);
        // 停止定位sdk
        mClient.stop();
    }
}